package com.example.blog.Utils;

import org.apache.tomcat.util.digester.Digester;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.StringReader;
import java.util.UUID;

public class SecurityUtil {
    //对密码进行加密
    public static String encrypt(String password) {
        //随机生成32的盐值
        String salt = UUID.randomUUID().toString().replace("-", "");
        //最终密码=md5(盐值+原始密码)
        String finalPassword =  DigestUtils.md5DigestAsHex((password + salt).getBytes());
        return salt + finalPassword;
    }
    //验证密码
    public static boolean verify(String password,String finalPassword) {
        if(!StringUtils.hasLength(password) || !StringUtils.hasLength(finalPassword)) {
            return false;
        }
        //判断长度
        if(finalPassword.length()!=64){
            return false;
        }
        String salt = finalPassword.substring(0,32);
        String securePassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        return (salt+securePassword).equals(finalPassword);
    }
//    public static void main(String[] args) {
//        String password = "123456";
//        System.out.println(encrypt(password));
//        String finalPassword = encrypt(password);
//        System.out.println(verify("123456",finalPassword));
//
//    }
}
